<template>
  <div>
    <navback title="登录" @back="goback()"></navback>
    <van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="password"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' }]"
  />
  <div class="btnColumn">
    <van-button round block type="info" native-type="submit">登录</van-button>
    <van-button round block type="warning" @click="gosubmit()" native-type="button">注册</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import {Login} from '@/api/user'
import JSEncrypt from 'jsencrypt'
import {mapGetters} from 'vuex'
import { Dialog, Toast } from 'vant'
import navback from '@/components/navback/navback'
export default {
  name:'Login',
  data(){
    return {
      username:'',
      password:''
    }
  },
  mounted(){
    
  },
  methods:{
    gosubmit(){
      this.$router.push('/user/register');
    },
    goback(){
      this.$router.go(-1);
    },
    async onSubmit(values){
      if(!this.PubKey){
        Toast.fail("取得公钥失败");
      }


      let username = values["username"];
      let password = values["password"];

      let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
      encryptor.setPublicKey(this.PubKey); // 设置公钥
      let rsaPassWord = encryptor.encrypt(password); // 对需要加密的数据进行加密
    
      let loginresult = await Login({username:username,password:rsaPassWord}).catch(err=>{return err});
      
      if(!loginresult.resultCode){
        Toast.fail(loginresult);
      }else{
        //token存在本地
        localStorage.setItem('authorization',loginresult.data.token);
        //用户信息、token放入store,
        await this.$store.dispatch('user/login',loginresult.data);
        
        let otherpath =  this.$router.currentRoute.query.redirect;
        let gopath = otherpath?otherpath:'/user/index';
        this.$router.push(gopath);//返回登录之前的页面
        

      }
      
      
    }
  },
  computed:{
    ...mapGetters([
      'PubKey'
    ])
  },
  components:{
    navback
  }
}
</script>

<style lang="scss" scoped>
  .btnColumn{
    box-sizing: border-box;
    padding: 10px;
    display: flex;
    flex-direction: column;
    align-content:space-around;
    & button{
      margin-top: 10px;
    }
  }
</style>